﻿using UnityEngine;
using System.Collections;

public class PoolComboNumber : MonoBehaviour {
	int currentDisplayedDigits = -1;
	public static int totalDigitsFinishedDisplaying = 0;
	bool isPlaying = false;

	GameObject refComboNumber;	//Ref_ComboNumber must has Animator disabled by default

	void Start () {
		refComboNumber = GameObject.Find("Ref_ComboNumber");
	}


	// Update is called once per frame
	void Update () {
		if( totalDigitsFinishedDisplaying >= currentDisplayedDigits ){
			isPlaying = false;
		}else{
			isPlaying = true;
		}
	}//Update

	public void showComboNumbers(int comboNumber, Vector2 positionToBeDisplayed){
		string comboNumberStr = comboNumber.ToString();
		float offsetX = 0.6f;	//assume, each number sprite is 0.6f width

		if(isPlaying){
			//destroy previous Combo Number Displays, then re-display again
			Debug.Log ("Destroying all displayed Combo Count");

			GameObject[] allComboNumberPreviouslyDisplayed = GameObject.FindGameObjectsWithTag("ComboNumber");
			for(int i=0; i<allComboNumberPreviouslyDisplayed.Length; i++){
				Destroy(allComboNumberPreviouslyDisplayed[i]);
			}

		}

		float totalOffsetX = (comboNumberStr.Length-1f)/2f;
		totalOffsetX *= offsetX;

		Vector2 numberPosition = new Vector2( (positionToBeDisplayed.x-totalOffsetX), positionToBeDisplayed.y);
		int singleComboNumber = 0;
		foreach(char singleDigitStr in comboNumberStr.ToCharArray()){
			//WARNING: No Sanity Check
			singleComboNumber = int.Parse(singleDigitStr.ToString());

			//duplicate a new ComboNumber (This is just a single digit)
			GameObject newObj = (GameObject)Instantiate(refComboNumber);
			newObj.name = "Copy_ComboNumber";	//specify it's a duplicated/Copy
			newObj.tag = "ComboNumber";
			newObj.transform.parent = this.transform;	//assign it to be a child of Pool_ComboNumber
			newObj.transform.position = numberPosition;	//adjust its position
			newObj.GetComponent<Animator>().SetInteger("numberToBePopped", singleComboNumber);
			newObj.GetComponent<Animator>().enabled = true;	//start playing the "pop number" animation

			numberPosition.x += offsetX;
		}

		currentDisplayedDigits = comboNumberStr.Length;
		totalDigitsFinishedDisplaying = 0;	//since we have display a new combo count, so we reset "total number of digits that's already finished displayed"

	}	//showComboNumbers()

}
